package com.muyu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muyu.system.domain.SysUserRole;
import com.muyu.system.mapper.SysUserRoleMapper;
import com.muyu.system.service.SysUserRoleService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户与角色关联业务实现层
 * @author dongzeliang
 * @version 1.0
 * @description: 用户与角色关联业务实现层
 * @date 2025/2/13 21:50
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {
    /**
     * 通过用户ID删除用户和角色关联
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public void deleteUserRoleByUserId(Long userId) {
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRole::getUserId, userId);
        this.remove(lambdaQueryWrapper);
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public long countUserRoleByRoleId(Long roleId) {
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRole::getRoleId, roleId);
        return this.count(lambdaQueryWrapper);
    }

    /**
     * 删除用户和角色关联信息
     *
     * @param userRole 用户和角色关联信息
     * @return 结果
     */
    @Override
    public void deleteUserRoleInfo(SysUserRole userRole) {
        //delete
        //        from sys_user_role
        //        where user_id = #{userId}
        //          and role_id = #{roleId}
        LambdaUpdateWrapper<SysUserRole> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(SysUserRole::getUserId, userRole.getUserId());
        lambdaUpdateWrapper.eq(SysUserRole::getRoleId, userRole.getRoleId());
        this.remove(lambdaUpdateWrapper);
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要删除的用户数据ID
     * @return 结果
     */
    @Override
    public void deleteUserRoleInfos(Long roleId, List<Long> userIds) {
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRole::getRoleId, roleId);
        lambdaQueryWrapper.in(SysUserRole::getUserId, userIds);
        this.remove(lambdaQueryWrapper);
    }

    /**
     * 删除用户与角色关联
     *
     * @param userIds 用户ID集合
     */
    @Override
    public void deleteUserRole(List<Long> userIds) {
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SysUserRole::getUserId, userIds);
        this.remove(lambdaQueryWrapper);
    }
}
